package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.context.LoginUserThreadLocal;
import com.atguigu.lease.common.exception.MyBusinessException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JWTUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    SystemUserService systemUserService;
    @Override
    public CaptchaVo getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX+UUID.randomUUID().toString();
        // 存入redis并设置过期时间为30分钟
        stringRedisTemplate.opsForValue().set(key, verCode,
                RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        // 将key和base64返回给前端
       return new CaptchaVo(specCaptcha.toBase64(),key);
    }

    @Override
    public String login(LoginVo loginVo) {
        //先判断是否为空
        if(!StringUtils.hasText(loginVo.getUsername()))
        {
            throw new MyBusinessException(ResultCodeEnum.PARAM_ERROR);
        }
        if(!StringUtils.hasText(loginVo.getPassword()))
        {
            throw new MyBusinessException(ResultCodeEnum.PARAM_ERROR);
        }
        if(!StringUtils.hasText(loginVo.getCaptchaCode()))
        {
            throw new MyBusinessException(ResultCodeEnum.PARAM_ERROR);
        }
        if(!StringUtils.hasText(loginVo.getCaptchaKey()))
        {
            throw new MyBusinessException(ResultCodeEnum.PARAM_ERROR);
        }

        //判断用户是否存在
        long count = systemUserService.count(new LambdaQueryWrapper<SystemUser>().
                eq(SystemUser::getUsername, loginVo.getUsername()));
        if(count==0)
        {
            throw new MyBusinessException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        //判断用户对应的密码是否正确
        SystemUser systemUser = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>().
                eq(SystemUser::getUsername, loginVo.getUsername())
                .eq(SystemUser::getPassword, DigestUtils.md5Hex(loginVo.getPassword())));
        if(systemUser==null)
        {
            throw new MyBusinessException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //判断验证码是否过期
        String s = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if(s==null)
        {
            throw new MyBusinessException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        //判断验证码是否正确
        if(!s.equalsIgnoreCase(loginVo.getCaptchaCode()))
        {
            throw new MyBusinessException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //判断用户是否被禁用
        if(systemUser.getStatus().equals(BaseStatus.DISABLE))
        {
            throw new MyBusinessException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //最后返回token
        return JWTUtil.createToken(systemUser.getId(),systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo getInfo() {
        LoginUserContext loginUserContext = LoginUserThreadLocal.getLoginUserContext();
        SystemUser byId = systemUserService.getById(loginUserContext.getUserId());
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setAvatarUrl(byId.getAvatarUrl());
    systemUserInfoVo.setName(byId.getName());
        return systemUserInfoVo;
    }

}
